<template>
  <div>
    <div style="margin: 10px 0">
      <el-input
        style="width: 200px"
        placeholder="请输入名称"
        v-model="name"
        suffix-icon="avatar"
      ></el-input>

      <el-input
        v-model="description"
        style="width: 200px"
        class="ml-5"
        placeholder="请输入描述"
        suffix-icon="message"
      ></el-input>

      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0; display: inline-flex">
      <el-button type="primary" icon="circle-plus" @click="handleAdd"
        >新增</el-button
      >
      <el-popconfirm
        width="200px"
        confirmButtonText="确定"
        cancelButtonText="取消"
        icon="check"
        iconColor="red"
        title="您确定批量删除吗？"
        @confirm="delBatch()"
      >
        <template #reference>
          <el-button type="danger" icon="remove">批量删除</el-button>
        </template>
      </el-popconfirm>

      <el-upload
        :show-file-list="false"
        accept="xlsx"
        :on-success="handleExcelImportSuccess"
        action="http://localhost:9090/role/import/"
        :limit="1"
        style="display: inline-block"
      >
        <!-- <el-button type="primary" icon="bottom" class="ml-5">导入</el-button> -->
      </el-upload>

      <!-- <el-button type="primary" icon="top" @click="exp" class="ml-5"
        >导出</el-button
      > -->
    </div>
    <el-table
      :data="tableData"
      border
      stripe
      header-cell-class-name="headerBg"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="ID"> </el-table-column>
      <el-table-column prop="name" label="名称"> </el-table-column>
      <el-table-column prop="flag" label="唯一标识"> </el-table-column>
      <el-table-column prop="description" label="描述"> </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="info" icon="menu" @click="selectMenu(scope.row)"
            >分配菜单</el-button
          >
          <el-button type="success" icon="edit" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            confirmButtonText="确定"
            cancelButtonText="取消"
            icon="check"
            iconColor="red"
            title="您确定删除吗？"
            @confirm="del(scope.row.id)"
          >
            <template #reference>
              <el-button type="danger" icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <div>
      <el-dialog title="角色信息:" v-model="dialogFormVisible" width="22%">
        <el-form :model="form" label-width="80px" size="small">
          <el-form-item label="名称:">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="唯一标识:">
            <el-input v-model="form.flag" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述:">
            <el-input v-model="form.description" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="randomTb" style="margin-right: 150px"
              >随 机</el-button
            >
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="菜单分配:" v-model="menuDialogVis" width="30%">
        <el-tree
          :props="props"
          :data="menuData"
          show-checkbox
          style="height: 200px"
          node-key="id"
          ref="tree"
          :check-strictly="true"
          :default-expanded-keys="expends"
          :default-checked-keys="checks"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span
                ><el-icon><apple /></el-icon>{{ data.name }}</span
              >
            </span>
          </template>
        </el-tree>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="randomTb" style="margin-right: 150px"
              >随 机</el-button
            >
            <el-button @click="menuDialogVis = false">取 消</el-button>
            <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { serverIp } from "../../public/config";

export default {
  name: "User",
  data() {
    const item = {
      date: "2016-05-02",
      name: "王小虎",
      address: "上海市普陀区金沙江路 1518 弄",
    };
    return {
      //tableData: Array(10).fill(item),
      serverIp: serverIp,
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: "",
      description: "",
      username: "",
      nickname: "",
      phone: "",
      email: "",
      address: "",
      msg: "青哥哥",
      collapseBtnClass: "fold",
      isCollapse: false,
      sideWidth: 200,
      myIcon: "fold",
      logoTextShow: true,
      form: [],
      dialogFormVisible: false,
      menuDialogVis: false,
      multipleTable: [],
      props: { label: "name" },
      expends: [],
      checks: [],
      mycustomicon: "apple",
      roleId: 0,
      roleFlag: "",
      menuData: [],
    };
  },
  created() {
    console.log("created");
    this.load();
  },
  methods: {
    load() {
      this.request
        .get("/role/page", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.name,
          },
        })
        .then((response) => {
          console.log("load");
          console.log(response);
          this.tableData = response.data.records;
          this.total = response.data.total;
        });
    },
    reset() {
      this.name = "";
      this.description = "";
      this.load();
    },
    handleSizeChange(pageSize) {
      console.log(pageSize);
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum);
      this.pageNum = pageNum;
      this.load();
    },
    handleAdd() {
      this.form = {};
      this.dialogFormVisible = true;
    },
    randomTb() {
      this.form.name = Math.random().toString(36).substring(2);
      this.form.description = Math.random().toString(36).substring(2);
      console.log(this.form);
    },
    save() {
      this.request.post("/role", this.form).then((response) => {
        if (response.code === "200") {
          this.$message.success("添加成功");
          this.dialogFormVisible = false;
          this.load();
        } else {
          this.$message.error("添加失败");
        }
        console.log(response.data);
      });
    },
    saveRoleMenu() {
      this.request
        .post("/role/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys())
        .then((response) => {
          if (response.code === "200") {
            this.$message.success("绑定成功");
            this.menuDialogVis = false;

            //现在就是解决管理员分配完了需要重登的问题，没啥必要看看就行
            // 操作管理员角色后需要重新登录。
            if (this.roleFlag === "ROLE_ADMIN") {
              this.$store.commit("logout");
            }
          } else {
            this.$message.error(response.msg);
          }
        });
    },
    handleEdit(row) {
      this.form = row;
      this.dialogFormVisible = true;
    },
    selectMenu(role) {
      this.menuDialogVis = true;
      this.roleId = role.id;
      this.roleFlag = role.flag;

      // 请求菜单数据
      this.request.get("/menu").then((response) => {
        this.menuData = response.data;

        // 把后台返回的id数据，处理成id数组。
        this.expends = this.menuData.map((v) => v.id);
      });

      this.request.get("/role/roleMenu/" + this.roleId).then((response) => {
        this.checks = response.data;

        this.request.get("/menu/ids").then((r) => {
          // 先渲染弹窗里的元素。
          const ids = r.data;
          ids.forEach((id) => {
            if (!this.checks.includes(id)) {
              this.$nextTick(() => {
                //使用 $nexttick处理未来元素，等到这个元素渲染完成之后，再去使用它
                this.$refs.tree.setChecked(id, false); // 先弹窗,再设置数值。??
              });
            }
          });
          this.menuDialogVis = true; // 控制打开窗口, 先弹窗,再设置数值。??
        });
      });
    },
    del(id) {
      this.request.delete("/role/" + id, this.form).then((response) => {
        if (response.code === "200") {
          this.$message.success("删除成功"); //顶部弹出提示框。
          this.dialogFormVisible = false;
          this.load();
        } else {
          this.$message.error("删除失败");
        }
        console.log(response.data);
      });
    },
    handleSelectionChange(val) {
      console.log(val);
      this.multipleTable = val;
    },
    delBatch() {
      //把对象数组。变成纯ID数组。
      let ids = this.multipleTable.map((item) => item.id); //[{},{},{}] =>  [1,2,3]
      this.request.post("/role/del/batch", ids).then((response) => {
        if (response.code === "200") {
          this.$message.success("批量删除成功"); //顶部弹出提示框。
          //this.dialogFormVisible = false;
          this.load();
        } else {
          this.$message.error("批量删除失败");
        }
        console.log(response.data);
      });
    },
    // handleCheckChange(data, checked, indeterminate) {
    //   console.log(data, checked, indeterminate);
    // },
  },
};
</script>
<style scoped>
.headerBg {
  background: #ccc !important;
}
</style>
